import { onMounted, ref } from 'vue'

export interface TemplateListItem {
  id: number
  name: string
  content: string
  comment: string
}

export function useGetTemplateList(baseUrl: string, params?: Record<string, any>) {
  const list = ref<TemplateListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  function buildQuery(params?: Record<string, any>): string {
    if (!params) return ''
    const query = Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&')
    return query ? `?${query}` : ''
  }

  async function fetchList() {
    loading.value = true
    error.value = null
    try {
      const url = `${baseUrl}/api/template/list${buildQuery(params)}`
      const res = await fetch(url)
      if (!res.ok) throw new Error('网络错误')
      list.value = await res.json()
    } catch (e: any) {
      error.value = e.message || '未知错误'
    } finally {
      loading.value = false
    }
  }

  onMounted(fetchList)

  return { list, loading, error, fetchList }
}
